package br.com.caim.viewcontroller.filtro;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.caim.email.excecoes.ExcecaoNegocio;
import br.com.caim.email.excecoes.ExcecaoSistema;

public class FiltroExcecoes implements Filter {

	public void destroy() {}
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("===== FILTRO DE EXCECOES INICIADO =====");
	}
	
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		
		try {
			chain.doFilter(request, response);
		// Trata excecoes na resposta para o cliente
		} catch (Exception e) {
			if(e instanceof ExcecaoNegocio || e instanceof ExcecaoSistema) {
				e.printStackTrace();
				request.getSession().setAttribute("excecao", e);
				response.sendRedirect("telaErro.do");
			} else if(e instanceof ServletException){
				e.printStackTrace();
				request.getSession().setAttribute("excecao", e);
				response.sendRedirect("telaErro.do");
			} else {
				e.printStackTrace();
				response.sendRedirect("telaErro.do");
			}
			
		}
		
	}	
}